﻿/// <reference path="../../../../_3rd part/SharePoint.d.ts"/>
var spdevlab;
(function (spdevlab) {
    (function (fields) {
        var DateBirthField = (function () {
            function DateBirthField(fieldName) {
                this._errorContainerId = null;
                this._monthContainerId = "";
                this._dayContainerId = "";
                this._yearContainerId = "";
                this._fieldName = fieldName;
            }
            DateBirthField.prototype._onGetValue = function () {
                var result = '';

                var monthContainer = document.getElementById(this._monthContainerId);
                var dayContainer = document.getElementById(this._dayContainerId);
                var yearContainer = document.getElementById(this._yearContainerId);

                var dValue = dayContainer.options[dayContainer.selectedIndex].value;
                var mValue = monthContainer.options[monthContainer.selectedIndex].value;
                var yValue = yearContainer.options[yearContainer.selectedIndex].value;

                if (dValue > -1 && mValue > -1 && yValue > -1) {
                    return mValue.toString() + "/" + dValue.toString() + "/" + yValue.toString();
                }

                return "";
            };

            DateBirthField.prototype._initValidators = function (renderCtx) {
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);

                var dbfFieldValidators = new SPClientForms.ClientValidation.ValidatorSet();

                if (formCtx.fieldSchema.Required) {
                    dbfFieldValidators.RegisterValidator(new spdevlab.fields.DateBirthFieldValidator());
                }

                formCtx.registerValidationErrorCallback(formCtx.fieldName, this.onError);
                formCtx.registerClientValidator(formCtx.fieldName, dbfFieldValidators);
            };

            DateBirthField.prototype._getDateTimeValue = function (fieldValue) {
                var result = {
                    activeDay: -1,
                    activeMonth: -1,
                    activeYear: -1
                };

                if (typeof fieldValue !== "undefined") {
                    var dateParts = [];

                    if (fieldValue.indexOf(":") > -1) {
                        dateParts = fieldValue.split(" ")[0].split('/');
                    } else {
                        dateParts = fieldValue.split("/");
                    }

                    result.activeMonth = dateParts[0];
                    result.activeDay = dateParts[1];
                    result.activeYear = dateParts[2];
                }

                return result;
            };

            DateBirthField.prototype._getUI = function (monthContainerId, dayContainerId, yearContainerId, fieldValue) {
                var result = [];

                var timeValue = this._getDateTimeValue(fieldValue);
                var months = spdevlab.fields.DateBirthField._months;

                // month UI
                result.push("<select id='" + monthContainerId + "' type='singleselect'>");
                result.push("<option value='-1'>Month...</option>");

                for (var i = 0; i < months.length; i++) {
                    var isSelected = (timeValue.activeMonth > -1 && (i + 1) == timeValue.activeMonth) == true ? "selected" : "";
                    result.push("<option value='" + (i + 1).toString() + "' " + isSelected + ">" + months[i].toString() + "</option>");
                }

                result.push("</select>");

                // day UI
                result.push("<select id='" + dayContainerId + "' type='singleselect'>");
                result.push("<option value='-1'>Day...</option>");
                for (var i = 1; i <= 31; i++) {
                    var isSelected = (timeValue.activeDay > -1 && (i) == timeValue.activeDay) == true ? "selected" : "";
                    result.push("<option value='" + i.toString() + "' " + isSelected + ">" + i.toString() + "</option>");
                }
                result.push("</select>");

                result.push(" | ");

                // year UI
                result.push("<select id='" + yearContainerId + "' type='singleselect'>");
                result.push("<option value='-1'>Choose...</option>");
                for (var i = 2013; i >= 1905; i--) {
                    var isSelected = (timeValue.activeYear > -1 && (i) == timeValue.activeYear) == true ? "selected" : "";
                    result.push("<option value='" + i.toString() + "' " + isSelected + ">" + i.toString() + "</option>");
                }
                result.push("</select>");

                return result.join("");
            };

            DateBirthField.prototype.newFormTemplate = function (renderCtx) {
                var _this = this;
                this._initValidators(renderCtx);

                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                formCtx.registerGetValueCallback(formCtx.fieldName, function () {
                    return _this._onGetValue();
                });

                var containerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + 'DateBirth_Field';

                this._monthContainerId = containerId + "_Month";
                this._dayContainerId = containerId + "_Day";
                this._yearContainerId = containerId + "_Year";

                return this._getUI(this._monthContainerId, this._dayContainerId, this._yearContainerId) + this._wrapErrorArea(renderCtx);
            };

            DateBirthField.prototype.editFormTemplate = function (renderCtx) {
                var _this = this;
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                var fieldValue = renderCtx.CurrentItem[renderCtx.CurrentFieldSchema.Name];

                this._initValidators(renderCtx);

                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                formCtx.registerGetValueCallback(formCtx.fieldName, function () {
                    return _this._onGetValue();
                });

                var containerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + 'DateBirth_Field';

                this._monthContainerId = containerId + "_Month";
                this._dayContainerId = containerId + "_Day";
                this._yearContainerId = containerId + "_Year";

                return this._getUI(this._monthContainerId, this._dayContainerId, this._yearContainerId, fieldValue) + this._wrapErrorArea(renderCtx);
            };

            DateBirthField.prototype.displayFormTemplate = function (renderCtx) {
                if (renderCtx != null && renderCtx.CurrentFieldValue != null) {
                    var fieldValue = renderCtx.CurrentFieldValue.toString();

                    var timeValue = this._getDateTimeValue(fieldValue);

                    if (timeValue.activeDay > -1 && timeValue.activeMonth > -1 && timeValue.activeYear > -1) {
                        return spdevlab.fields.DateBirthField._months[timeValue.activeMonth - 1].toString() + " " + timeValue.activeDay.toString() + ", " + timeValue.activeYear.toString();
                    }

                    return fieldValue;
                }

                return '';
            };

            DateBirthField.prototype.viewTemplate = function (renderCtx, field, listItem, listSchema) {
                var fieldValue = "";

                if (renderCtx != null && renderCtx.CurrentItem != null) {
                    fieldValue = renderCtx.CurrentItem[field.Name];
                    var timeValue = this._getDateTimeValue(fieldValue);

                    if (timeValue.activeDay > -1 && timeValue.activeMonth > -1 && timeValue.activeYear > -1) {
                        return spdevlab.fields.DateBirthField._months[timeValue.activeMonth - 1].toString() + " " + timeValue.activeDay.toString() + ", " + timeValue.activeYear.toString();
                    }
                }

                return fieldValue;
            };

            DateBirthField.prototype._wrapErrorArea = function (renderCtx) {
                var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(renderCtx);
                var errorContainerId = formCtx.fieldName + '_' + formCtx.fieldSchema.Id + '_DateBirth_Error';

                this._errorContainerId = errorContainerId;

                return "<div></div><span id='" + errorContainerId + "' class='ms-formvalidation ms-csrformvalidation'></span>";
            };

            DateBirthField.prototype.onError = function (error) {
                if (this._errorContainerId != null) {
                    document.getElementById(this._errorContainerId).innerHTML = "<span role='alert'>" + error.errorMessage + "</span>";
                }
            };

            DateBirthField.prototype.Init = function () {
                var _this = this;
                var fieldName = this._fieldName;
                var visaFieldTemplates = {
                    Templates: {
                        Fields: {}
                    }
                };

                visaFieldTemplates.Templates.Fields[fieldName] = {};

                visaFieldTemplates.Templates.Fields[fieldName]["View"] = function (renderCtx, field, listItem, listSchema) {
                    return _this.viewTemplate(renderCtx, field, listItem, listSchema);
                };

                visaFieldTemplates.Templates.Fields[fieldName]["NewForm"] = function (renderCtx) {
                    return _this.newFormTemplate(renderCtx);
                };

                visaFieldTemplates.Templates.Fields[fieldName]["EditForm"] = function (renderCtx) {
                    return _this.editFormTemplate(renderCtx);
                };

                visaFieldTemplates.Templates.Fields[fieldName]["DisplayForm"] = function (renderCtx) {
                    return _this.displayFormTemplate(renderCtx);
                };

                SPClientTemplates.TemplateManager.RegisterTemplateOverrides(visaFieldTemplates);
            };
            DateBirthField._months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
            return DateBirthField;
        })();
        fields.DateBirthField = DateBirthField;

        var DateBirthFieldValidator = (function () {
            function DateBirthFieldValidator() {
            }
            DateBirthFieldValidator.prototype.Validate = function (value) {
                var hasError = value == "";
                var errorMsg = hasError ? "Please, fill out birthdate." : '';

                return new SPClientForms.ClientValidation.ValidationResult(hasError, errorMsg);
            };
            return DateBirthFieldValidator;
        })();
        fields.DateBirthFieldValidator = DateBirthFieldValidator;
    })(spdevlab.fields || (spdevlab.fields = {}));
    var fields = spdevlab.fields;
})(spdevlab || (spdevlab = {}));

(function () {
    var field = new spdevlab.fields.DateBirthField("DateBirthField");
    field.Init();
})();
